import { h, type StyleValue } from "vue";
import {
  getFabAreaSelectOptions,
  queryDeviceList,
  getFabList,
  queryPositionList,
  getFabPMCategorySelectOptions,
  queryFactoryStatusOptions
} from "@/api/modules/fab";
import dayjs from "dayjs";
import weekday from "dayjs/plugin/weekday";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
import "dayjs/locale/zh-cn";
import { PxIcon } from "px-ui";
import { ArrowLeftBold, ArrowRightBold } from "@px-ui/icons-vue";
import pm_flag from "@/assets/svg/common/pm_flag.svg?component";

dayjs.extend(isSameOrBefore);
dayjs.extend(isSameOrAfter);
dayjs.extend(weekday);
dayjs.locale("zh-cn");

/**
 *  计划状态
 **/
const colors = new Map([
  [
    "processing",
    {
      color: "#00cb78",
      backgroundColor: "#d0f7e7"
    }
  ],
  [
    "inactive",
    {
      color: "#909399",
      backgroundColor: "#e9e9eb"
    }
  ],
  [
    "waiting",
    {
      color: "#f59e0b",
      backgroundColor: "#fde68a"
    }
  ]
]);

export const tagMapOption = new Map([
  [
    "PROCESSING",
    {
      value: "PROCESSING",
      label: "执行中",
      rgb: "16, 185, 129"
      // color: "RGBA(16, 185, 129, 1)",
      // borderColor: "RGBA(16, 185, 129, .25)",
      // backgroundColor: "RGBA(16, 185, 129, .15)"
    }
  ],
  [
    "INACTIVE",
    {
      value: "INACTIVE",
      label: "未激活",
      rgb: "120, 120, 120"
      // color: "#909399",
      // backgroundColor: "#e9e9eb"
    }
  ],
  [
    "WAITING",
    {
      value: "WAITING",
      label: "待执行",
      rgb: "245, 158, 0"
      // color: "#f59e0b",
      // backgroundColor: "#fde68a"
    }
  ],

  [
    "processing",
    {
      value: "processing",
      label: "processing",
      rgb: "16, 185, 129"
      // color: "RGBA(16, 185, 129, 1)",
      // borderColor: "RGBA(16, 185, 129, .25)",
      // backgroundColor: "RGBA(16, 185, 129, .15)"
    }
  ],
  [
    "inActive",
    {
      value: "inActive",
      label: "inActive",
      rgb: "120, 120, 120"
      // color: "#909399",
      // backgroundColor: "#e9e9eb"
    }
  ],
  [
    "waiting",
    {
      value: "waiting",
      label: "waiting",
      rgb: "245, 158, 0"
      // color: "#f59e0b",
      // backgroundColor: "#fde68a"
    }
  ]
]);

/**
 * @description:   获取计划状态样式
 * @param {*} status
 * @return {*}
 */
export const planStatusStyleFn = (status = "inactive") => {
  const style = {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: "6px 10px",
    borderRadius: "4px",
    lineHeight: 1,
    color: "#909399",
    backgroundColor: "#e9e9eb"
  };
  const c = colors.get(status.toLowerCase()) || {};
  return { ...style, ...c };
};

/**
 * @description:    获取search配置信息
 * @param {*} chart    1 厂务设备    2 FAB机台
 * @param {*} chartType    gunter  甘特图   chart  table图
 * @param {function} cb
 * @return {Array<CommonSearch.SearchOption>}
 */
export const useSearchOption = async (chart = 1, chartType = "gunter", cb?: (data: any) => null): Promise<Array<CommonSearch.SearchOption>> => {
  const pmAeraMap = new Map();
  cb && cb(pmAeraMap);

  const deviceName: CommonSearch.SearchOption = {
    label: "设备名称",
    key: "deviceIdOrPlanNum",
    value: null,
    type: "select",
    remote: true,
    selectRemoteApi: queryDeviceList,
    getParams: (deviceName: string) => deviceName,
    mapOption: ({ deviceId = "", deviceName = "" }: any) => ({ value: deviceId, label: `${deviceId}-${deviceName}` }),
    placeholder: "请选择设备"
  };

  const fabName: CommonSearch.SearchOption = {
    label: "机台编号",
    key: "deviceIdOrPlanNum",
    value: null,
    type: "select",
    remote: true,
    selectRemoteApi: getFabList,
    getParams: (fabName: string) => fabName,
    mapOption: ({ eqpId: value = "", eqpId: label = "" }: any) => ({ value, label }),
    placeholder: "请选择机台编号"
  };

  const position: CommonSearch.SearchOption = {
    label: "位置",
    key: "deviceArea",
    value: null,
    type: "select",
    remote: true,
    selectRemoteApi: queryPositionList,
    getParams: (position: string) => position,
    mapOption: ({ positionCode: value = "", positionName: label = "" }: any) => ({ value, label }),
    placeholder: "请选择位置"
  };

  const deviceArea: CommonSearch.SearchOption = {
    label: "区域",
    key: "deviceArea",
    value: null,
    type: "select",
    axiosApi: getFabAreaSelectOptions,
    // mapOption: ({ areaId: value = "", areaCode: label = "" }: any) => ({ value, label }),
    formatOption: (res: Array<any>): Array<any> => {
      return res?.map(({ areaId: value = "", areaCode: label = "" }: any) => ({ value, label }))?.filter(({ value, label }) => !!value && !!label);
    },
    placeholder: "请选择区域"
  };

  // 厂务
  const category_1: CommonSearch.SearchOption = {
    label: "类型",
    key: "category",
    value: null,
    type: "select",
    axiosApi: getFabPMCategorySelectOptions,
    mapOption: ({ code: value = "", name: label = "" }: any) => ({ value, label }),
    placeholder: "请选择类型"
  };

  // 机台
  const category_2: CommonSearch.SearchOption = {
    label: "类型",
    key: "category",
    value: null,
    type: "select",
    typeCode: "FAB_PM_CATEGORY",
    placeholder: "请选择类型"
  };

  const factoryStatus: CommonSearch.SearchOption = {
    label: "状态",
    key: "planStatus",
    value: null,
    type: "select",
    axiosApi: queryFactoryStatusOptions,
    mapOption: ({ code: value = "", name: label = "" }: any) => ({ value, label }),
    placeholder: "请选择状态"
  };

  const planStatus: CommonSearch.SearchOption = {
    label: "状态",
    key: "planStatus",
    value: null,
    type: "select",
    typeCode: "FAB_PM_PLAN_STATUS",
    placeholder: "请选择状态"
  };

  const s = dayjs().subtract(7, "day").startOf("date").format("YYYY-MM-DD HH:mm:ss");
  const e = dayjs().add(21, "day").endOf("date").format("YYYY-MM-DD HH:mm:ss");
  // const startDate: CommonSearch.SearchOption = {
  //   label: "维保时间",
  //   key: "startDate",
  //   realKeys: ["startDate", "endDate"],
  //   value: chartType === "gunter" ? [s, e] : [],
  //   type: "datetimerange",
  //   span: 4
  // };

  const pmTimeStart: CommonSearch.SearchOption = {
    label: "维保时间",
    key: "pmTimeStart",
    realKeys: ["pmTimeStart", "pmTimeEnd"],
    value: chartType === "gunter" ? [s, e] : [],
    type: "daterange",
    span: 4
  };

  const factoryOptions = [deviceName, position, category_1, factoryStatus];
  const fabOptions = [fabName, deviceArea, category_2, planStatus];
  if (chartType === "chart") {
    factoryOptions.push(pmTimeStart);
    fabOptions.push(pmTimeStart);
  }
  if (chart === 1) {
    return factoryOptions;
  } else if (chart === 2) {
    return fabOptions;
  }
};

/**
 * @description: 获取table表格的表头（cloumns）信息 （gunter）
 * @param {*} chart  1 厂务设备     2 FAB机台
 * @param {*} chartType  gunter  甘特图     chart  table图
 * @return {*}
 */
export const useTableCloumns = (
  chart?: number,
  chartType?: string,
  startDate?: string,
  endDate?: string,
  cb?: (d: any) => void,
  cb2?: (s: any) => void,
  cb3?: (scope: any) => void,
  cb4?: (scope: any) => void
): Array<CommonTable.TableCloumnsType> => {
  const preWeek = (n: number) => {
    const s = dayjs(startDate).add(n, "week").startOf("week").format("YYYY-MM-DD HH:mm:ss");
    const e = dayjs(s).add(3, "week").endOf("week").format("YYYY-MM-DD HH:mm:ss");
    cb && cb({ s, e });
    startDate = s;
    endDate = e;
  };

  const pmHeader = (index: number) => {
    const day = dayjs(startDate).add(index, "week").startOf("week").add(3, "day");
    const year = day.year();
    const week = day.week();
    const title = `${year}年 第${week}周`;
    const hd = title => <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>{title}</div>;
    const iconStyle = {
      fontSize: "18px",
      color: "var(--px-color-primary)",
      cursor: "pointer"
    };
    if (index === 0) {
      return (
        <div style={{ display: "flex", alignItems: "center" }}>
          <PxIcon style={iconStyle} onClick={() => preWeek(-1)}>
            <ArrowLeftBold />
          </PxIcon>
          {hd(title)}
        </div>
      );
    } else if (index === 3) {
      return (
        <div style={{ display: "flex", alignItems: "center" }}>
          {hd(title)}
          <PxIcon style={iconStyle} onClick={() => preWeek(1)}>
            <ArrowRightBold />
          </PxIcon>
        </div>
      );
    } else {
      return hd(title);
    }
  };

  /**
   * @description:  过滤当周的计划列表
   * @param {any} scope
   * @param {string} startDate
   * @param {number} index
   * @return {*}
   */
  const filterList = (scope: any, startDate: string, index: number): Array<any> => {
    const {
      row: { itemDomList = null }
    } = scope;
    if (!itemDomList?.length) return [];
    return itemDomList.filter(item => {
      const { earlyDate_, lateDate_ } = item;
      const currentDay = dayjs(startDate).add(index, "week").startOf("week").add(3, "day");
      const earlyDay = dayjs(earlyDate_).startOf("week").add(3, "day");
      const lateDay = dayjs(lateDate_).startOf("week").add(3, "day");
      const currentYear = currentDay.year();
      const earlyYear = earlyDay.year();
      const lateYear = lateDay.year();
      const currentWeek = currentDay.week();
      const earlyWeek = earlyDay.week();
      const lateWeek = lateDay.week();
      return currentYear === earlyYear && currentYear === lateYear && currentWeek === earlyWeek && currentWeek === lateWeek;
    });
  };

  const pmProgress = (scope: any, index: number) => {
    const pmPlanList = filterList(scope, startDate, index);
    let currentFirstDate = dayjs(startDate).add(index, "week").startOf("week").format("YYYY-MM-DD HH:mm:ss"); // 当周第一天
    const currentLastDate = dayjs(currentFirstDate).add(6, "day").endOf("date").format("YYYY-MM-DD HH:mm:ss"); // 当周最后一天
    const formatWeek = (n: number) => (n > 0 ? n : 7);
    const getGanttList = (list: Array<any>) => {
      return list.reduce((pre, cur, index, ar) => {
        const { earlyDate_ = "", dueDate_ = "", lateDate_ = "", backgroundColor = "" } = cur;
        if (index === 0) {
          if (formatWeek(dayjs(earlyDate_).day()) > formatWeek(dayjs(currentFirstDate).day())) {
            const flex = formatWeek(dayjs(earlyDate_).day()) - formatWeek(dayjs(currentFirstDate).day());
            const e = { type: 0, flex };
            if (dayjs().isSameOrBefore(dayjs(earlyDate_), "day") && dayjs().isSameOrAfter(dayjs(currentFirstDate), "day")) {
              const flex_t = formatWeek(dayjs().day()) - formatWeek(dayjs(currentFirstDate).day());
              e["flex_t"] = flex_t;
            }
            pre.push(e);
          }
        } else if (formatWeek(dayjs(earlyDate_).day()) > formatWeek(dayjs(currentFirstDate).day()) + 1) {
          const flex = formatWeek(dayjs(earlyDate_).day()) - formatWeek(dayjs(currentFirstDate).day()) - 1;
          const e = { type: 0, flex };
          if (dayjs().isSameOrBefore(dayjs(earlyDate_), "day") && dayjs().isSameOrAfter(dayjs(currentFirstDate).add(1, "day"), "day")) {
            const flex_t = formatWeek(dayjs().day()) - formatWeek(dayjs(currentFirstDate).day()) - 1;
            e["flex_t"] = flex_t;
          }
          pre.push(e);
        }
        currentFirstDate = lateDate_;
        const i = {
          type: 1,
          backgroundColor,
          flex: formatWeek(dayjs(lateDate_).day()) - formatWeek(dayjs(earlyDate_).day()) + 1,
          flex_f: dueDate_ ? formatWeek(dayjs(dueDate_).day()) - formatWeek(dayjs(earlyDate_).day()) + 1 : 0
        };
        if (dayjs().isSameOrBefore(dayjs(lateDate_), "day") && dayjs().isSameOrAfter(dayjs(earlyDate_), "day")) {
          const flex_t = formatWeek(dayjs().day()) - formatWeek(dayjs(earlyDate_).day());
          i["flex_t"] = flex_t;
        }
        pre.push(i);
        if (index === ar.length - 1) {
          if (formatWeek(dayjs(currentLastDate).day()) > formatWeek(dayjs(lateDate_).day())) {
            const flex = formatWeek(dayjs(currentLastDate).day()) - formatWeek(dayjs(lateDate_).day());
            const e = { type: 0, flex };
            if (dayjs().isSameOrBefore(dayjs(currentLastDate), "day") && dayjs().isSameOrAfter(dayjs(lateDate_), "day")) {
              const flex_t = formatWeek(dayjs().day()) - formatWeek(dayjs(lateDate_).day()) - 1;
              e["flex_t"] = flex_t;
            }
            pre.push(e);
          }
        }
        return pre;
      }, []);
    };

    const todayBackgroundColor = "var(--px-color-primary-light-9)";

    const commonStyle = {
      display: "flex",
      gap: "1px",
      backgroundColor: "transparent",
      height: "36px"
    };

    const commonCellStyle = {
      flex: 1,
      backgroundColor: "transparent",
      height: "36px",
      display: "flex",
      alignItems: "flex-end",
      gap: "1px"
    };

    const commonStripStyle = {
      backgroundColor: "transparent",
      height: "12px"
    };

    const clickHandler = scope => {
      cb2 && cb2(scope);
    };

    const progressDom = (item: any) => {
      const { type = 0, flex = 0, flex_f = 0, flex_t = null, backgroundColor = "transparent" } = item;
      const domStyle: StyleValue = { color: backgroundColor, width: "12px", height: "12px", margin: "auto", marginTop: "-12px" };
      const f_dom = (backgroundColor = "transparent", todayBackgroundColor = "transparent") => (
        <div style={{ ...commonCellStyle, backgroundColor: todayBackgroundColor }}>
          <div style={{ ...commonStripStyle, flex: 1, cursor: "pointer", backgroundColor }} onClick={() => clickHandler(scope)}>
            {h(pm_flag, { style: { ...domStyle } })}
          </div>
        </div>
      );
      switch (type) {
        case 0:
          const f_b = new Array(flex).fill("b");
          return (
            <div style={{ ...commonStyle, flex }}>
              {f_b.map((item, index) => (
                <div style={{ ...commonCellStyle, backgroundColor: flex_t === index ? todayBackgroundColor : "transparent" }}></div>
              ))}
            </div>
          );
        case 1:
          const f_r = new Array(flex).fill("f");
          if (flex_f && f_r.length === 1) {
            return f_dom(backgroundColor, flex_t === 0 ? todayBackgroundColor : "");
          }
          return (
            <div style={{ ...commonCellStyle, flex }}>
              {f_r.map((item, index) => {
                if (flex_f && index + 1 === flex_f) {
                  return f_dom(backgroundColor, flex_t === index ? todayBackgroundColor : "");
                } else {
                  return (
                    <div style={{ ...commonCellStyle, backgroundColor: index === flex_t ? todayBackgroundColor : "transparent" }}>
                      <div style={{ ...commonStripStyle, flex: 1, cursor: "pointer", backgroundColor }} onClick={() => clickHandler(scope)}></div>
                    </div>
                  );
                }
              })}
            </div>
          );
        default:
          return <div style={{ ...commonStripStyle, flex }}></div>;
      }
    };

    const getDefaultGanttList = (): Array<any> => {
      if (dayjs().isSameOrBefore(dayjs(currentLastDate), "day") && dayjs().isSameOrAfter(dayjs(currentFirstDate), "day")) {
        const flex_t = dayjs().diff(dayjs(currentFirstDate), "day");
        const i = {
          flex: 7,
          flex_t,
          type: 0
        };
        return [i];
      } else {
        return [];
      }
    };

    let ganttList = [];
    if (pmPlanList?.length) {
      ganttList = getGanttList(pmPlanList);
    } else {
      ganttList = getDefaultGanttList();
    }
    ganttList = ganttList.reduce((pre, cur) => {
      const { flex, flex_f, flex_t } = cur;
      let num = 0;
      do {
        const item = { ...cur, flex: 1 };
        delete item.flex_f;
        delete item.flex_t;
        if (num === flex_f - 1) {
          item["flex_f"] = 1;
        }
        if (num === flex_t) {
          item["flex_t"] = 0;
        }
        pre.push(item);
        num++;
      } while (num < flex);
      return pre;
    }, []);
    return <div style={{ ...commonStyle }}>{ganttList.map(item => progressDom(item))}</div>;
  };

  //   chart  1 厂务设备     2 FAB机台
  const arr = [
    {
      label: "科室",
      prop: "className",
      width: 50
    },
    {
      label: chart === 1 ? "设备编号" : "机台编号",
      prop: "deviceId",
      width: chart === 1 ? 80 : 120,
      cloumnClick: (scope: any) => {
        cb4 && cb4(scope);
      }
    },
    {
      label: "计划编号",
      prop: "planNo",
      width: 80,
      cloumnClick:
        chart === 1
          ? (scope: any) => {
              cb3 && cb3(scope);
            }
          : (scope: any) => {
              cb2 && cb2(scope);
            }
    },
    {
      label: "计划名称",
      prop: "planTitle",
      width: 80
    },
    {
      label: "状态",
      prop: "planStatus", // 1、厂务  PROCESSING  INACTIVE  WAITING    2、fab机台  processing  inActive  waiting
      width: 90,
      tagMapOption,
      defaultTagValue: "PROCESSING",
      mapRow: ({ row: { planStatus: value = "", planStatusName: label = "" } }: any) => ({ value, label })
    },
    {
      prop: "itemDtoList",
      renderHeader() {
        return () => pmHeader(0);
      },
      children: [
        {
          label: "一",
          width: 36,
          props: { "class-name": "pm-gunter" },
          render(scope) {
            return () => pmProgress(scope, 0);
          }
        },
        {
          label: "二",
          width: 36
        },
        {
          label: "三",
          width: 36
        },
        {
          label: "四",
          width: 36
        },
        {
          label: "五",
          width: 36
        },
        {
          label: "六",
          width: 36
        },
        {
          label: "日",
          width: 36
        }
      ]
    },
    {
      prop: "itemDtoList",
      renderHeader() {
        return () => pmHeader(1);
      },
      children: [
        {
          label: "一",
          width: 36,
          props: { "class-name": "pm-gunter" },
          render(scope) {
            return () => pmProgress(scope, 1);
          }
        },
        {
          label: "二",
          width: 36
        },
        {
          label: "三",
          width: 36
        },
        {
          label: "四",
          width: 36
        },
        {
          label: "五",
          width: 36
        },
        {
          label: "六",
          width: 36
        },
        {
          label: "日",
          width: 36
        }
      ]
    },
    {
      prop: "itemDtoList",
      renderHeader() {
        return () => pmHeader(2);
      },
      children: [
        {
          label: "一",
          width: 36,
          props: { "class-name": "pm-gunter" },
          render(scope) {
            return () => pmProgress(scope, 2);
          }
        },
        {
          label: "二",
          width: 36
        },
        {
          label: "三",
          width: 36
        },
        {
          label: "四",
          width: 36
        },
        {
          label: "五",
          width: 36
        },
        {
          label: "六",
          width: 36
        },
        {
          label: "日",
          width: 36
        }
      ]
    },
    {
      prop: "itemDtoList",
      renderHeader() {
        return () => pmHeader(3);
      },
      children: [
        {
          label: "一",
          width: 36,
          props: { "class-name": "pm-gunter" },
          render(scope) {
            return () => pmProgress(scope, 3);
          }
        },
        {
          label: "二",
          width: 36
        },
        {
          label: "三",
          width: 36
        },
        {
          label: "四",
          width: 36
        },
        {
          label: "五",
          width: 36
        },
        {
          label: "六",
          width: 36
        },
        {
          label: "日",
          width: 36
        }
      ]
    }
  ];

  if (chart === 1) {
    arr.splice(1, 0, {
      label: "系统",
      prop: "systemName",
      width: 50
    });
    // arr.unshift({
    //   label: "系统",
    //   prop: "systemName",
    //   width: 60
    // });
  }

  return arr;
};

/**
 * @description:  获取table表格的表头（cloumns）信息 （chart）
 * @param {number} chart  1 厂务设备     2 FAB机台
 * @param {function} cb  回调
 * @return {*}
 */
export const useTableCloumns2 = (
  chart?: number,
  cb?: (scope: any) => void,
  cb2?: (scope: any) => void,
  cb3?: (scope: any) => void
): Array<CommonTable.TableCloumnsType> => {
  const a_0 = {
    label: "科室",
    prop: "className"
  };

  const a = {
    label: chart === 1 ? "设备编号" : "机台编号",
    prop: "deviceId",
    sortable: "custom",
    cloumnClick: (scope: any) => {
      cb2 && cb2(scope);
    }
  };

  const b = {
    label: "所属系统",
    prop: "systemName"
  };

  const b_1 = {
    label: "子系统",
    prop: "childSystemName"
  };

  const c = {
    label: chart === 1 ? "位置" : "区域",
    prop: "deviceArea"
  };

  const d = {
    label: "计划编号",
    prop: "planNo",
    cloumnClick:
      chart === 1
        ? (scope: any) => {
            cb && cb(scope);
          }
        : (scope: any) => {
            cb3 && cb3(scope);
          }
  };

  const e = {
    label: "标题",
    prop: "planTitle"
  };

  const f = {
    label: "类型",
    prop: "category"
  };

  const g = {
    label: "状态",
    prop: "planStatus", // 1、厂务  PROCESSING  INACTIVE  WAITING    2、fab机台  processing  inActive  waiting
    width: 100,
    tagMapOption,
    defaultTagValue: "PROCESSING",
    mapRow: ({ row: { planStatus: value = "", planStatusName: label = "" } }: any) => ({ value, label })
  };

  const h = {
    label: "最早开始时间",
    prop: "earlyDate",
    sortable: "custom",
    width: 110
  };

  const i = {
    label: "计划执行时间",
    prop: "dueDate",
    sortable: "custom",
    width: 110
  };

  const j = {
    label: "最晚结束时间",
    prop: "lateDate",
    sortable: "custom",
    width: 110
  };

  const k = {
    label: "上次作业时间",
    prop: "lastJobTime",
    sortable: "custom",
    width: 110
  };

  if (chart === 1) {
    return [a_0, a, b, b_1, c, d, e, f, g, h, i, j, k];
  } else {
    return [a, c, d, e, f, g, h, i, j, k];
  }
};

/**
 * @description:  改造原装计划表，按周来分
 * @param {Array} list
 * @return {*}
 */
export const mapList = (list: Array<any>): Array<any> => {
  if (!list?.length) return [];
  // 按周拆开
  const arr_1 = list.reduce((pre, cur) => {
    const { earlyDate: earlyDate_ = "", dueDate: dueDate_ = "", lateDate: lateDate_ = "" } = cur;
    // 设置颜色
    /**
     * 底色变化逻辑：
     * 新建计划默认颜色为蓝色
     * 已执行完的计划为灰色 ------   暂时不考虑（产品同步--2024-9-5）
     * 当前时间< Early Date 时,不变色
     * Early Date<=当前时间<Due Date 时,底色改成黄色
     * Due Date<=当前时间<Late Date 时,底色改成橙色
     * 当前时间> Late Date 时,底色改成红色
     */
    // 默认 蓝色
    let backgroundColor = "#0061FF";
    // 蓝色
    if (dayjs().isBefore(dayjs(earlyDate_))) {
      backgroundColor = "#0061FF";
    }
    // // 灰色
    // if (dayjs().valueOf() >= dayjs(dueDate_).valueOf()) {
    //   backgroundColor = "#C2C2C2";
    // }
    // 黄色
    if (dayjs().isSameOrAfter(dayjs(earlyDate_)) && dayjs().isSameOrBefore(dayjs(dueDate_))) {
      // backgroundColor = "#FFFF00";
      backgroundColor = "#FFA500";
    }
    // 橙色
    if (dayjs().isSameOrAfter(dayjs(dueDate_)) && dayjs().isSameOrBefore(dayjs(lateDate_))) {
      backgroundColor = "#FFA500";
    }
    // 红色
    if (dayjs().isAfter(dayjs(lateDate_))) {
      backgroundColor = "#FF0000";
    }
    cur["backgroundColor"] = backgroundColor;
    // 注意  需要考虑跨年的情况
    // 注意  需要考虑跨年的情况
    // 注意  需要考虑跨年的情况
    if (dayjs(earlyDate_).week() === dayjs(lateDate_).week()) {
      // 在同一周内
      pre.push({ ...cur, earlyDate_, dueDate_, lateDate_ });
    } else if (dayjs(earlyDate_).week() === dayjs(dueDate_).week()) {
      // earlyDate 和 dueDate 在同一周
      const item_1 = { ...cur, earlyDate_, dueDate_, lateDate_: dayjs(dueDate_).endOf("week").format("YYYY-MM-DD HH:mm:ss") };
      const item_2 = { ...cur, earlyDate_: dayjs(lateDate_).startOf("week").format("YYYY-MM-DD HH:mm:ss"), lateDate_ };
      pre.push(item_1);
      pre.push(item_2);
    } else if (dayjs(dueDate_).week() === dayjs(lateDate_).week()) {
      // dueDate 和 lateDate 在同一周
      const item_1 = { ...cur, earlyDate_, lateDate_: dayjs(earlyDate_).endOf("week").format("YYYY-MM-DD HH:mm:ss") };
      const item_2 = { ...cur, earlyDate_: dayjs(dueDate_).startOf("week").format("YYYY-MM-DD HH:mm:ss"), dueDate_, lateDate_ };
      pre.push(item_1);
      pre.push(item_2);
    }
    return pre;
  }, []);
  if (!arr_1?.length) return [];
  // 去重  目前支持 一天 前后的重叠
  return arr_1.reduce((pre, cur, index) => {
    const { earlyDate_ = "", lateDate_ = "" } = cur;
    if (index === 0) {
      pre.push(cur);
    } else {
      const lastCur = [...pre].pop();
      const { earlyDate_: lastEarlyDate = "", dueDate_: lastDueDate = "", lateDate_: lastLateDate = "" } = lastCur;
      const earlyDateTimeStamp = dayjs(earlyDate_).startOf("day").valueOf();
      const lateDateTimeStamp = dayjs(lateDate_).startOf("day").valueOf();
      const lastEarlyDateTimeStamp = dayjs(lastEarlyDate).startOf("day").valueOf();
      const lastDueDateTimeStamp = dayjs(lastDueDate).startOf("day").valueOf();
      const lastLateDateTimeStamp = dayjs(lastLateDate).startOf("day").valueOf();
      if (earlyDateTimeStamp > lastLateDateTimeStamp) {
        pre.push(cur);
      } else {
        if (earlyDateTimeStamp > lastEarlyDateTimeStamp && earlyDateTimeStamp <= lastLateDateTimeStamp) {
          if (lateDateTimeStamp > lastLateDateTimeStamp) {
            pre.pop();
            if (lastDueDateTimeStamp) {
              if (lastDueDateTimeStamp < earlyDateTimeStamp) {
                const item = {
                  ...lastCur,
                  earlyDate_: lastEarlyDate,
                  dueDate_: lastDueDate,
                  lateDate_: dayjs(earlyDate_).subtract(1, "day").format("YYYY-MM-DD HH:mm:ss")
                };
                pre.push(item);
                pre.push(cur);
              } else {
                const item = { ...lastCur, earlyDate_: lastEarlyDate, lateDate_: dayjs(earlyDate_).subtract(1, "day").format("YYYY-MM-DD HH:mm:ss") };
                pre.push(item);
                pre.push(cur);
              }
            } else {
              const item = { ...lastCur, earlyDate_: lastEarlyDate, lateDate_: dayjs(earlyDate_).subtract(1, "day").format("YYYY-MM-DD HH:mm:ss") };
              pre.push(item);
              pre.push(cur);
            }
          }
        } else if (earlyDateTimeStamp === lastEarlyDateTimeStamp) {
          if (lastLateDateTimeStamp < lateDateTimeStamp) {
            pre.pop();
            pre.push(cur);
          }
        } else {
          pre.pop();
          pre.push(cur);
        }
      }
    }
    return pre;
  }, []);
};

/**
 * @description: map 甘特图 table数据
 * @param {Array} data
 * @return {*}
 */
export const useGunterTableData = (data: Array<any>): Array<any> => {
  return data.map(item => {
    item["itemDomList"] = mapList(item.itemDtoList);
    return item;
  });
};
